
package com.borqs.music.ui.online;

import static com.borqs.music.tasks.SongTask.PAGE_COUNT;
import static com.borqs.music.ui.adapter.OnlineTrackListAdapter.TYPE_NORMAL;
import static com.borqs.music.ui.adapter.OnlineTrackListAdapter.TYPE_STATUS;
import static com.borqs.music.util.AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.borqs.music.R;
import com.borqs.music.executor.MusicExecutor;
import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskAdapter;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.model.SongInfo;
import com.borqs.music.tasks.GetHotSearchTask;
import com.borqs.music.tasks.SearchSongsTask;
import com.borqs.music.ui.adapter.OnlineTrackListAdapter;
import com.borqs.music.ui.adapter.OnlineTrackListAdapter.Status;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.SharedPreferencesCompat;

public class OnlineSearchActivity extends OnlineBaseActivity {
    private static final String HOT_SEARCHS_KEY = "hot_searchs";
    private EditText searchEditText;

    private OnlineTrackListAdapter mAdapter;
    private List<SongInfo> mSongList = new ArrayList<SongInfo>();
    private ArrayAdapter<String> mHotAdapter;
    private List<String> mHotSearchs = new ArrayList<String>();
    private String mCurrentKeywords;
    private int mCurrentPage = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // search bar
        ViewStub searchStub = (ViewStub) findViewById(R.id.stub_search);
        View searchBar = searchStub.inflate();
        ImageButton btn = (ImageButton) searchBar.findViewById(R.id.search_input_btn);
        btn.setOnClickListener(mSearchClickListener);

        searchEditText = (EditText) searchBar.findViewById(R.id.search_input_edit);

        ListView listView = getListView();
        // reset the empty view set by OnlineBaseActivity
        ViewGroup parentView = (ViewGroup) listView.getParent();
        LinearLayout newEmptyView = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.online_search_hot,
                parentView, false);
        GridView gridView = (GridView) newEmptyView.findViewById(R.id.hot_search_grid);
        mHotAdapter = new ArrayAdapter<String>(this, R.layout.online_search_hot_item,
                mHotSearchs);
        gridView.setAdapter(mHotAdapter);
        gridView.setOnItemClickListener(mHotItemClickListener);

        SharedPreferences pref = getSharedPreferences("Music", MODE_WORLD_READABLE);
        String hotStr = pref.getString(HOT_SEARCHS_KEY, "");
        String[] hots = hotStr.split(",");
        mHandler.obtainMessage(MSG_UPDATE_HOT, Arrays.asList(hots)).sendToTarget();
        View oldEmptyView = parentView.findViewById(android.R.id.empty);
        parentView.removeView(oldEmptyView);
        // replace the position of oldEmptyView index = 2
        parentView.addView(newEmptyView, 2);
        listView.setEmptyView(newEmptyView);

        mAdapter = new OnlineTrackListAdapter(this, mSongList);
        listView.setAdapter(mAdapter);
        sendGetHotsRequest();
    }

    private AdapterView.OnItemClickListener mHotItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String content = (String) parent.getItemAtPosition(position);
            searchEditText.setText(content);
            
            if (!checkActiveNetworkStatus()) {
                return;
            }

            if (!content.equalsIgnoreCase(mCurrentKeywords)) {
                mAdapter.clear();
                mCurrentKeywords = content;
                mCurrentPage = 0;
                sendSearchRequest(content, mCurrentPage);
            }
        }
    };

    private View.OnClickListener mSearchClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String input = searchEditText.getText().toString();
            input = input.trim();
            if (input.length() == 0) {
                showToast(R.string.online_search_on_input);
                return;
            }

            if (!checkActiveNetworkStatus()) {
                return;
            }

            if (!input.equalsIgnoreCase(mCurrentKeywords)) {
                mAdapter.clear();
                mCurrentKeywords = input;
                mCurrentPage = 0;
                sendSearchRequest(input, mCurrentPage);
            }
        }
    };

    private final int MSG_LOAD_START = 1;
    private final int MSG_LOAD_COMPLETE = 2;
    private final int MSG_LOAD_FAILED = 3;
    private final int MSG_UPDATE_HOT = 4;

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_START:
                    mAdapter.setStatus(Status.LOADING);
                    mAdapter.notifyDataSetChanged();
                    break;
                case MSG_LOAD_COMPLETE:
                    @SuppressWarnings("unchecked")
                    List<SongInfo> songs = (List<SongInfo>) msg.obj;
                    mSongList.addAll(songs);
                    if (songs.size() < PAGE_COUNT) {
                        mAdapter.setStatus(Status.NONE);
                    } else {
                        mAdapter.setStatus(Status.MORE);
                    }
                    mAdapter.notifyDataSetChanged();

                    if (mAdapter.getCount() == 0) {
                        String prompt = getString(R.string.online_search_no_result,
                                mCurrentKeywords);
                        showToast(prompt);
                    }
                    mCurrentPage++;
                    break;
                case MSG_LOAD_FAILED:
                    mAdapter.setStatus(Status.FAILED);
                    mAdapter.notifyDataSetChanged();
                    break;
                case MSG_UPDATE_HOT:
                    @SuppressWarnings("unchecked")
                    List<String> hots = (List<String>) msg.obj;
                    mHotSearchs.clear();
                    mHotSearchs.addAll(hots);
                    mHotAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        if (!checkActiveNetworkStatus()) {
            return;
        }
        
        int type = mAdapter.getItemViewType(position);
        if (type == TYPE_STATUS) {
            if (mAdapter.getStatus() != Status.LOADING) {
                sendSearchRequest(mCurrentKeywords, mCurrentPage);
            }
            return;
        }

        if (type == TYPE_NORMAL) {
            playsong(mSongList, position);
            return;
        }
    }

    private void sendSearchRequest(String keywords, int page) {
        Message msg = mHandler.obtainMessage(MSG_LOAD_START);
        mHandler.sendMessage(msg);
        String ticket = getTicket();
        SearchSongsTask task = new SearchSongsTask(searchListener, ticket, keywords, page);
        MusicExecutor exec = MusicExecutor.getInstance();
        exec.execute(task);
    }

    private TaskListener searchListener = new TaskAdapter() {
        @Override
        public void onDone(Task task) {
            Message msg = mHandler.obtainMessage(MSG_LOAD_COMPLETE);
            msg.obj = task.getResult();
            mHandler.sendMessage(msg);
        }

        @Override
        public void onFail(Task task) {
            Message msg = mHandler.obtainMessage(MSG_LOAD_FAILED);
            mHandler.sendMessage(msg);
        }
    };

    private void sendGetHotsRequest() {
        String ticket = getTicket();
        GetHotSearchTask task = new GetHotSearchTask(getHotListener, ticket);
        MusicExecutor exec = MusicExecutor.getInstance();
        exec.execute(task);
    }

    private TaskListener getHotListener = new TaskAdapter() {
        @Override
        public void onDone(Task task) {
            @SuppressWarnings("unchecked")
            final List<String> hots = (List<String>) task.getResult();
            SharedPreferences pref = getSharedPreferences("Music", MODE_WORLD_READABLE);
            SharedPreferences.Editor editor = pref.edit();
            StringBuffer hotStr = new StringBuffer();
            for (String str : hots) {
                hotStr.append(str);
                hotStr.append(",");
            }

            editor.putString(HOT_SEARCHS_KEY, hotStr.toString());
            SharedPreferencesCompat.apply(editor);

            mHandler.obtainMessage(MSG_UPDATE_HOT, hots).sendToTarget();
        }
    };

    private String getTicket() {
        String ticket = AccountUtils.getUserData(this, BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
        return ticket;
    }
}
